﻿using CoreWebApiNuGet.Convention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;

namespace CoreWebApiNuGet.ProgramExtend
{
    /// <summary>
    /// 添加Api版本控制配置
    /// </summary>
    public static class AddApiVersioningProgram
    {
        /// <summary>
        /// Api版本控制
        /// </summary>
        /// <param name="services"></param>
        /// <param name="apiVersionHeaderName"></param>
        /// <returns></returns>
        public static IServiceCollection AddApiVersioning(this IServiceCollection services, string apiVersionHeaderName = "api-version")
        {
            services.AddControllers(options =>
            {
                options.Conventions.Add(new ControllerRouteConvention());
            });

            IApiVersionReader apiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), new HeaderApiVersionReader(apiVersionHeaderName));

            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true; // 启用报告 API 版本
                options.ApiVersionReader = apiVersionReader;
                options.AssumeDefaultVersionWhenUnspecified = true; // 当未指定版本时，假定默认版本
                options.DefaultApiVersion = new ApiVersion(1, 0); // 设置默认 API 版本
            });

            services.AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV"; // 定义 API 版本格式
                options.SubstituteApiVersionInUrl = true; // 在 URL 中替换 API 版本
            });

            return services;
        }
    }
}
